package com.itsc.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.itsc.util.page.Page;


@SuppressWarnings("unchecked")
public class BaseDao<T> {

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		return this.sessionFactory.getCurrentSession();
	}

	/**
	 * 增加
	 * 
	 * @param t
	 */
	public void save(T t) {
		getSession().save(t);
	}

	/**
	 * 修改
	 * 
	 * @param t
	 */
	public void update(T t) {
		//getSession().update(t);
		getSession().merge(t);
	}
	
	/**
	 * 删除
	 * 
	 * @param t
	 */
	public void delete(T t) {
		getSession().delete(t);
	}

	/**
	 * 根据id查找
	 * 
	 * @param hql
	 * @param id
	 * @return
	 */
	public T selectById(String hql, Integer id) {
		try {
			Query query = getSession().createQuery(hql);
			query.setInteger(0, id);
			List<T> list = query.list();
			return list.get(0);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * 查找全部
	 * 
	 * @param hql
	 * @return
	 */
	public List<T> selectAll(String hql) {
		try {
			Query query = getSession().createQuery(hql);
			List<T> list = query.list();
			return list;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * 计算对应表所有记录数量
	 * @param hql
	 * @return
	 */
	public int getCount(String hql) {
		Query query = getSession().createQuery(hql);
		return new Long((long) query.uniqueResult()).intValue();
	}
	
	/**
	 * 一页显示的记录条数
	 * @param hql
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<T> getPage(String hql, Page page) {

		Query query = getSession().createQuery(hql);
		query.setFirstResult(page.getBeginIndex());
		query.setMaxResults(page.getPageSize());
		List<T> list = query.list();
		return list;
	}

}
